package com.utils;

import com.sftpserver.service.SftpServerService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.UserAuthFactory;
import org.apache.sshd.server.auth.password.UserAuthPasswordFactory;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.shell.ProcessShellCommandFactory;
//import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;


import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutorService;


@Slf4j(topic = "服务启动工具类")
public class SftpServerUtils {
    private long timeout;
    private ExecutorService workerPool;
    private boolean lazySessionCreation = true;

    @SneakyThrows
    public static SftpServerService setupSftpServer(String username, String password, String host, int port, String sftpPath)  {
        /*如果目录不存在则新建*/
        File file =new File(sftpPath); //如果文件夹不存在则创建
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("//不存在"); file.mkdir();
        } else {
            System.out.println("目录存在");
        }

        Path rootSftpDir = Paths.get(sftpPath).toAbsolutePath();


        List<UserAuthFactory> userAuthFactories = new ArrayList<>();
        userAuthFactories.add(new UserAuthPasswordFactory());
        List sftpCommandFactory = new ArrayList();
        sftpCommandFactory.add(new SftpSubsystemFactory());
        SshServer sshd = SshServer.setUpDefaultServer();

        sshd.stop();

        sshd.setHost(host);
        sshd.setPort(port);

        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());

        sshd.setUserAuthFactories(userAuthFactories);

        sshd.setCommandFactory(new ProcessShellCommandFactory());

        sshd.setSubsystemFactories(sftpCommandFactory);

        sshd.setPasswordAuthenticator((usernameAuth, passwordAuth, session) -> {
            if ((username.equals(usernameAuth)) && (password.equals(passwordAuth))) {
                sshd.setFileSystemFactory(new VirtualFileSystemFactory(rootSftpDir));
                return true;
            }
            return false;
        });

        sshd.start();
        return new SftpServerService(sshd, rootSftpDir);
    }

    public static void stopServer(SftpServerService sftpServerBean) throws IOException {
        sftpServerBean.getSshServer().stop();
//        Files.walk(sftpServerBean.getRootPath())
//                .sorted(Comparator.reverseOrder())
//                .map(Path::toFile)
//                .forEach(File::delete);
    }


}
